/**
 * Created by Administrator on 2017/4/20.
 */


var Card9Room = require('../CARD9/room').Card9Room;

var Const = require('./const');
var SubCode = require('../subCode');

var RoundStatus = {
    'WAITING': 1,   // 等待其它玩家准备
    'SELECTBASE': 2, //设置了基础分
    'READY': 3,     // 就绪，开始游戏
    'PLAY': 4,     // 玩家选牌
}

exports.YQWCard9Room = Card9Room.extend({
    _roundStatus: RoundStatus.WAITING,

    _dealerIndex: 0,           // 庄家坐位
    _selectWaitTime: 0,        // 开始选牌的时间

    init: function (rid, creator, msg) {
        //msg.options.roomPlayerNum = msg.options.playersNum;
        this._super(rid, creator, msg);

        this._roundStatus = RoundStatus.WAITING;
        //延时任务锁
        this.selectedScore = false;
        this.selected = false;
        this.robedDeal = false;
        //延时任务ID
        this.selectedScoreID = 0;
        this.selectedID = 0;
        this.robDealID = 0;
        //抢庄任务时间
        this.robDealTime = 0;
        this.robDealEndTime = 0;
        //选分任务时间
        this.selectScoreTime = 0;
        this.selectScoreEndTime = 0;
        //选牌任务时间
        this.selectCardTime = 0;
        this.selectCardEndTime = 0;
        //庄位置
        this._dealerIndex = 0;

        this.fixScore = 0;
        if(this.getOption('FixScore')){
            var fixedscore = this.getOption('FixScore');
            switch (fixedscore){
                case 1:
                    this.fixScore = 1;
                    break;
                case 2:
                    this.fixScore = 2;
                    break;
                case 3:
                    this.fixScore = 5;
                    break;
                case 4:
                    this.fixScore = 8;
                    break;
                case 5:
                    this.fixScore = 10;
                    break;
            }
        }

    },
    reset: function () {
        this.selectedScore = false;
        this.selected = false;
        this.robedDeal = false;

        this.selectScoreTime = 0;
        this.selectScoreEndTime = 0;

        this.selectCardTime = 0;
        this.selectCardEndTime = 0;

        this.robDealTime = 0;
        this.robDealEndTime = 0;

        clearTimeout(this.robDealID);
        clearTimeout(this.selectedScoreID);
        clearTimeout(this.selectedID);
    },

    /******************************************************************
     * 重载的接口
     ******************************************************************/

    getRoundInfo: function () {
        var info = this._super();
        // info.robDealerWaitMS = this.getHideOption("robDealerWaitMS");
        // info.selectWaitMS = this.getHideOption("selectWaitMS");
        return info;
    },

    getReconnectInfo: function (rePlayer) {
        var info = this._super(rePlayer);
        info.dealer = this._dealerIndex;

        info.selectScoreStartTime = this.selectScoreTime;
        info.selectScoreEndTime = this.selectScoreEndTime;

        info.selectCardStartTime = this.selectCardTime;
        info.selectCardEndTime = this.selectCardEndTime;

        info.robDealStartTime = this.robDealTime;
        info.robDealEndTime = this.robDealEndTime;

        return info;
    },

    onAfterPlayerReady: function (player) {
        this._super(player);

        var subConfig = this.getSubConfig();
        //检查是否开始游戏
        
        if (!this.isPlaying() && this.getReadyPlayerCount() >= subConfig.roomPlayerMin
            && this.getPlayerCount() == this.getReadyPlayerCount()) {
            //&& this.getPlayerCount() == this.getOption("playersNum")
            //this._startNewRoundAfter(this.getHideOption("startWaitMS"));
            this._roundStatus = RoundStatus.READY;
            


        }
    },

    checkStartNewRound: function () {
        if (this.isPlaying()) {
            return false;
        }

        if (this._roundStatus != RoundStatus.READY) {
            return false;
        }

        return true;
    },
    //1
    // onBeforeStartNewRound: function () {
    //     this._super();
    //     this._selectWaitTime = 0;
    // },
    //2
    onAfterStartNewRound: function () {
        this._super();
        this._startPlay();
    },

    onSettlement: function () {
        this._super();

        this.enumPlaying(function (eIndex, ePlayer) {
            ePlayer.settlementPattern();
        });
    },


    getRoomConfig: function () {
        var cfg = this._super();
        //cfg.destroyWaitTime = 200;
        cfg.respDestroyIgnore = 1;
        cfg.resetDestroyOnNewRound = 0;
        return cfg;
    },
    onCurRoundFinished: function () {
        this._super();
        this._roundStatus = RoundStatus.WAITING;
        this.reset();

    },
    onDestroy: function () {
        clearTimeout(this.selectedScoreID);
        clearTimeout(this.selectedID);
        clearTimeout(this.robDealID);
    },


    /******************************************************************
     * 功能接口
     ******************************************************************/
    handleRobDeal:function (player, msg, callback) {
        if (!this.isPlaying()) {
            callback({ code: Code.ROOM_NOT_PLAYING }); return;
        }
        if(!this.getOption('DealType') != 2){
            callback({code:Code.SUB_TYPE_INVALID});return;
        }
        if (!msg.hasOwnProperty('robDeal') || isNaN(msg.robDeal)) {
            callback({ code: Code.ARGS_INVALID }); return;
        }
        if(player.robDeal != 0){
            callback({code: Code.ARGS_INVALID});return;
        }
        if(msg.robDeal == 1){
            player.robDeal = 1; // 抢
        }else{
            player.robDeal = 2; // 不抢
        }
        callback({});
        this.broadcast("onPlayerRobDeal", {
            playerIndex: player.getIndex(),
            robDeal: msg.robDeal
        });
        var isAllSet = true;
        this.enumPlaying(function (eIndex, ePlayer) {
            if(ePlayer.robDeal == 0){
                isAllSet = false;
            }
        });

        if (isAllSet) {
            this.robedDeal = true;
            if(this.getOption('FixScore') != 0){
                this._waitSelectBaseScore();
            }else{
                this._waitSelectCards();
            }
        }
    },

    handleSelectBaseScore: function (player, msg, callback) {
        if (!this.isPlaying()) {
            callback({ code: Code.ROOM_NOT_PLAYING }); return;
        }
        if(!this.getOption('FixScore')){
            callback({code:Code.SUB_TYPE_INVALID});return;
        }

        if (player.firstScore != 0 && player.secondScore != 0) {
            callback({ code: SubCode.TASK_UNMATCHED }); return;
        }

        if (!msg.hasOwnProperty('score') || isNaN(msg.score)) {
            callback({ code: Code.ARGS_INVALID }); return;
        }

        var score = parseInt(msg.score);
        if (score != 5 && score != 10 && score != 15  && score != 20) {
            callback({ code: Code.ARGS_VALUE_WRONG }); return;
        }
        if(player.isDealer()){
            callback({code: Code.ARGS_VALUE_WRONG});return;
        }
        if((player.firstScore+ score) >= 20){
            callback({code: Code.ARGS_VALUE_WRONG});return;
        }
        player.setBaseScore(score);
        this.broadcast("onPlayerBaseScore", {
            playerIndex: player.getIndex(),
            firstScore: player.firstScore,
            secondScore:player.secondScore,
        });
        callback({});

        var isAllSet = true;
        this.enumPlaying(function (eIndex, ePlayer) {
            if (!ePlayer.isDealer() && !ePlayer.isSetBaseScore()) {
                isAllSet = false;
            }
        });

        if (isAllSet) {
            this.selectedScore = true;
            this._afterSelectedBaseScore();
            //this._dealSelectedBase();
        }
    },
    _afterSelectedBaseScore:function () {
        this._waitSelectCards();
    },

    handleSelectCards: function (player, msg, callback) {
        if (!msg.cards) {
            callback({ code: Code.ARGS_INVALID }); return;
        }

        if (!player.isPlaying()) {
            callback({ code: Code.PLAYER_NOT_PLAYING }); return;
        }

        if (!this.isPlaying()) {
            callback({ code: Code.ROOM_NOT_PLAYING }); return;
        }

        if (this.isCurRoundFinished()) {
            callback({ code: Code.ROOM_ROUND_FINISHED }); return;
        }
        if(!this.selected){
            callback({ code: Code.ARGS_INVALID }); return;
        }
        var cards = msg.cards;
        if (!ExObject.isArray(cards)) {
            callback({ code: Code.ARGS_VALUE_WRONG }); return;
        }

        if (!player.setSelectedCards(cards)) {
            callback({ code: SubCode.CARD_NOT_EXIST }); return;
        }

        callback({});

        this.broadcast("onPlayerSelectCards", {
            playerIndex: player.getIndex(),
            selectCards: cards.slice()
        });
        player.isSelected = true;

        var isAllSelected = true;
        this.enumPlaying(function (eIndex, ePlayer) {
            if (!ePlayer.isSelectedCards()) {
                isAllSelected = false;
            }
        });

        if (isAllSelected && this.selected == false) {
            this.selected = true;
            this.settlementCurRound();
        }
    },

    _startPlay: function () {
        //
        if(this.getSubType() != 'GUOCARD9'){
            var MS = this.getOption('DealType');
            //轮庄
            if(MS == 1 ){
                if(this._dealerIndex == 0){
                    this._dealerIndex = 1;
                    this.broadcast("onDealerChanged", {
                        dealer: this._dealerIndex,
                    });
                }else{
                    this._dealerIndex = this.getNextPlayer(this._dealerIndex);
                    this.broadcastReplay("onDealerChanged", {
                        dealer: this._dealerIndex,
                    });
                }
                if(!this.fixScore){
                    this.enumPlaying(function(eIndex,ePlayer){
                       ePlayer.setBaseScore(this.fixScore);
                       ePlayer.setBaseScore(this.fixScore);
                    }.bind(this));
                    this._waitSelectCards();
                    return;
                }
                this._waitSelectBaseScore();

            }else if(MS == 2){
                //抢庄
                this._waitRobDeal();

            }else if(MS == 3){
                //霸王庄
                this._dealerIndex = 1;
                this.broadcast("onDealerChanged", {
                    dealer: this._dealerIndex,
                });
                if(!this.fixScore){
                    this.enumPlaying(function(eIndex,ePlayer){
                        ePlayer.setBaseScore(this.fixScore);
                        ePlayer.setBaseScore(this.fixScore);
                    }.bind(this));
                    this._waitSelectCards();
                    return;
                }
                this._waitSelectBaseScore();
            }
        }


    },

    _waitRobDeal:function () {
        var startTime = Date.parse(new Date());
        this.broadcast("onWaitRobDeal", {
            "startTime": startTime,
            "endTime":startTime + this.getHideOption('robDealWaitMS'),
        });
        this.selectedID = setTimeout(function () {
            if (this.robedDeal)
                return;
            this.robedDeal = true;

            this._afterRobDeal();
        }.bind(this), this.getHideOption("robDealWaitMS"));
    },
    _afterRobDeal:function () {
        this.enumPlaying(function(eIndex,ePlayer){
            if(ePlayer.robedDeal == 0){
                ePlayer.robedDeal = 2;
                this.broadcast("onPlayerRobDeal", {
                    playerIndex: eIndex,
                    robDeal: 2
                });
            }
        }.bind(this));
        var arr = [];
        var arr1 = [];
        this.enumPlaying(function (eIndex, ePlayer) {
            if(ePlayer.robedDeal == 1) {
                arr.push(eIndex);
            } else {
                arr1.push(eIndex);
            }
        });
        if(!arr.length){
            this._dealerIndex = Ext.randArray(arr1);
            this.broadcastReplay("onDealerChanged", {
                dealer: this._dealerIndex,
            });
        }else{
            this._dealerIndex = Ext.randArray(arr);
            this.broadcastReplay("onDealerChanged", {
                dealer: this._dealerIndex,
            });
        }

        if(this.getOption('FixScore') != 0){
            this._waitSelectBaseScore();
            return;
        }
        this._waitSelectCards();
    },

    _waitSelectCards: function () {
        this._roundStatus = RoundStatus.PLAY;
        var startTime = Date.parse(new Date());
        this.broadcast("onWaitSelectCards", {
            "startTime": startTime,
            "endTime":startTime + this.getHideOption('selectWaitMS'),
        });

        this.selectedID = setTimeout(function () {
            if (this.selected)
                return;
            this.selected = true;
            this.settlementCurRound();
        }.bind(this), this.getHideOption("selectWaitMS"));
    },

    _waitSelectBaseScore: function () {
        var startTime = Date.parse(new Date());
        this.broadcast("onWaitBaseScore", {
            "startTime": startTime,
            "endTime":startTime + this.getHideOption('selectScoreWaitMS'),
        });
        this.selectedScoreID = setTimeout(function () {
            if (!this.isPlaying()) {
                return;
            }

            if (this._roundStatus != RoundStatus.READY) {
                return;
            }
            if(this.selectedScore){
                return;
            }

            this.enumPlaying(function (eIndex, ePlayer) {
                if (ePlayer.firstScore == 0) {
                    ePlayer.firstScore = 1;
                    ePlayer.secondScore = 1;
                    this.broadcast("onPlayerBaseScore", {
                        playerIndex: ePlayer.getIndex(),
                        firstScore: ePlayer.firstScore,
                        secondScore: ePlayer.secondScore,
                    });
                }else if(ePlayer.secondScore == 0){
                    if(ePlayer.firstScore == 20){
                        ePlayer.secondScore = 0;
                    }else{
                        ePlayer.secondScore = 1;
                    }
                }

            }.bind(this));
            this.selectedScore = true;
            this._afterSelectedScore();

            //this._dealRobDealerAllSet();

        }.bind(this), this.getHideOption("selectScoreWaitMS"));
    },
    _afterSelectedScore:function () {
            this.initPlayersHandCards();
            this._waitSelectCards();
    },

});